<template>
  <div class="page-box">
    <universal-table :columns="columns" :fetch-data="fetchTableData" permission-prefix="sys:community" :show-selection="true"
      :show-index="true" :export-file-name="'社区'" :init-search-form="searchForm" @edit="handleEdit" @delete="handleDelete"
      @reset="reset" @status-change="handleStatusChange" ref="table" :showAdd="true" @add="handAdd">

      <!-- 搜索区域扩展 -->
      <template #searchExtend>
        <el-form-item prop="approved_status">
         <el-cascader v-model="searchForm.town_id" :options="options" :props="cascaderProps" style="width: 400px;"
           @change="handleChange"></el-cascader>
        </el-form-item>
      </template>
    </universal-table>

    <!-- 编辑弹窗 -->
    <el-dialog title="社区信息" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="autoClose" @open="onDialogOpen" @close="onDialogClose">
      <ReviewDetail v-if="currentRow && cascaderVisible" :formData="currentRow" :optionData="optionsItem"
      :key="cascaderKey" @community="handleApprove" @communityCancel="communityCancel" ref="childRef"/>
    </el-dialog>

  </div>
</template>

<script>
  import UniversalTable from "@/components/TableComponent.vue";
  import ReviewDetail from "./ReviewDetail.vue";

  export default {
    components: {
      UniversalTable,
      ReviewDetail
    },
    data() {
      return {
        cascaderVisible:false,
        autoClose:false,
        cascaderKey:0,
        cascaderProps: {
          emitPath: false, // 默认是 true，如果你只想拿到最后一级就设为 false
          checkStrictly: false // 是否可选择任意一级，默认 false
        },
        searchForm:{
           town_id:0,
        },
        dialogVisible: false,
        currentRow: null,
        options:[],
        optionsItem:[],
        columns: [
          {
            prop: "name",
            label: "社区名称"
          },
          {
            prop: "province_name",
            label: "所在省"
          },
          {
            prop: "city_name",
            label: "所在市"
          },
          {
            prop: "area_name",
            label: "所在区|县"
          },
          {
            prop: "town_name",
            label: "所在街道|乡镇"
          },
          {
            prop: "create_time",
            label: "创建时间"
          },
        ],
      };
    },
    computed: {

    },
    mounted() {
      this.initData();
    },
    methods: {
      // 获取表格数据
      async fetchTableData(params = {}) {
        const postData = Object.assign({}, params, this.searchForm);
        try {
          const result = await this.$httpRequest.get('/community/list', postData)
          console.log('-------fetchTableData----', result)
          return result
        } catch (e) {
          this.$message.error(e.message)
          throw e // 保持错误继续向上传递
        }

      },
      onDialogClose(){
        this.cascaderVisible = false;
      },
      onDialogOpen(){
        console.log('----onDialogOpen---')
       this.cascaderVisible = true;
          this.$nextTick(() => {
            this.$nextTick(() => {
              this.$refs.childRef && this.$refs.childRef.loadOptions();
            });
          });
      },
      initData() {
        const loading = this.$loading({lock: true});
        this.$httpRequest.get('/community/tree').then(result => {
          console.log('--getRegionsList--3----', result)
          this.options = result
          this.optionsItem = result
          loading.close();
        }).catch(e => {
          this.$message.error(e.message)
          loading.close();
        });
      },

      handleChange(value){
         console.log('--value---handleChange---', value)
      },

      //重置
      reset() {
        this.searchForm.town_id=0


      },
      handAdd(){
        this.cascaderKey++
        this.currentRow = {}
        this.dialogVisible = true;
      },
      // 编辑
      handleEdit(row) {

        // 打开编辑对话框逻辑
        this.currentRow = {
          ...row
        }; // 可深拷贝
        this.cascaderKey++
        this.dialogVisible = true;
      },

      // 删除
      async handleDelete(row) {
        let payload={}
        payload.id = row.id*1
        console.log('--handleDelete--payload-', payload)
        this.$httpRequest.delete('/community/del', payload).then(result => {
          console.log('--approved---result------', result)
          if (result.code == 0) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除成功')
          }
        }).catch(e => {
          this.$message.error(e.message)
        });
      },

      // 状态变更
      async handleStatusChange(row) {
        console.log("状态变更:", row);
        this.$message.success("状态更新成功");
      },

      //取消编辑
      communityCancel(){
        this.dialogVisible = false;
      },
      handleApprove(payload) {
        console.log("--社区信息：--", payload);
        if(!payload.id){
          this.$httpRequest.post('/community/add', payload).then(result => {
            console.log('--approved---result------', result)
            if (result.code == 0) {
              this.$message.success('添加小区成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('添加小区失败')
            }
          }).catch(e => {
            this.$message.error(e.message)
          });

        }else{
          this.$httpRequest.post('/community/edit', payload).then(result => {
            console.log('--approved---result------', result)
            if (result.code == 0) {
              this.$message.success('编辑小区成功')
              this.$refs.table.refresh()
            } else {
              this.$message.error('编辑小区失败')
            }
          }).catch(e => {
            this.$message.error(e.message)
          });


        }
        this.dialogVisible = false;
      },
    },
  };
</script>

<style>
  .page-box {
    padding: 20px;

  }
</style>
